package com.idrive.adapter;

import java.util.List;

import android.content.ActivityNotFoundException;
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageButton;
import android.widget.TextView;
import android.widget.Toast;

import com.idrive.R;
import com.idrive.database.dto.CallLog;

public class CallLogAdapter extends BaseAdapter {
	private Context context;
	private final List<CallLog> callLogList;

	public CallLogAdapter(Context context, List<CallLog> list) {
		this.context = context;
		this.callLogList = list;
	}

	public View getView(final int position, View convertView, ViewGroup parent) {

		LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);

		final View gridView;

		if (convertView == null) {

			// gridView = new View(context);

			// get layout from mobile.xml
			gridView = inflater.inflate(R.layout.layout_call_log, null);

			final CallLog callLog = callLogList.get(position);

			// set value into textview
			TextView textView = (TextView) gridView.findViewById(R.id.telephone_number);
			textView.setText(callLog.getTelephone());

			textView = (TextView) gridView.findViewById(R.id.date_time);
			textView.setText(callLog.getTime());

			textView = (TextView) gridView.findViewById(R.id.log_event);
			textView.setText(callLog.getEvent());

			ImageButton deleteButton = (ImageButton) gridView.findViewById(R.id.delete_imageButton);
			deleteButton.setOnClickListener(new View.OnClickListener() {
				public void onClick(View v) {

					callLogList.remove(position);
					gridView.invalidate();

				}
			});

			ImageButton outgoingButton = (ImageButton) gridView.findViewById(R.id.outgoing_imageButton);
			outgoingButton.setOnClickListener(new View.OnClickListener() {
				public void onClick(View v) {

					try {
						Intent callIntent = new Intent(Intent.ACTION_CALL);
						callIntent.setData(Uri.parse("tel:" + callLog.getTelephone()));
						context.startActivity(callIntent);
					} catch (ActivityNotFoundException e) {
						Toast.makeText(context, e.toString(), Toast.LENGTH_LONG).show();
					}

				}
			});

		} else {
			gridView = (View) convertView;
		}

		return gridView;
	}

	public int getCount() {
		return callLogList.size();
	}

	public Object getItem(int position) {
		return null;
	}

	public long getItemId(int position) {
		return 0;
	}
}
